<template>
  <div>
    <div class="box-border p-12px">
      <div>
        <SubTitle title="基本信息" />
        <el-descriptions :column="descInfo.column">
          <el-descriptions-item
            :label="item.label"
            v-for="(item, index) in descInfo.columns"
            :key="index"
          >
            <span v-if="item.key == 'fileName'">{{ descInfo.data.fileName || '--' }} </span>
            <span v-else-if="item.key == 'source'">{{ descInfo.data[item.key] || '--' }}</span>
            <span v-else-if="item.key == 'fileFingerprint'">
              <el-tooltip placement="top" :content="descInfo.data.md5?.toString() || '无'">
                <span>MD5,</span>
              </el-tooltip>
              <el-tooltip placement="top" :content="descInfo.data.kfs?.toString() || '无'">
                <span>KFS,</span>
              </el-tooltip>
              <el-tooltip placement="top" :content="descInfo.data.pfs?.toString() || '无'">
                <span>PFS,</span>
              </el-tooltip>
              <el-tooltip placement="top" :content="descInfo.data.psa?.toString() || '无'">
                <span>PSA</span>
              </el-tooltip>
            </span>
            <span v-else>
              {{ form[item.key] || '--' }}
            </span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="mt-16px">
        <SubTitle title="分类分级信息" />
        <el-descriptions column="1" class="mt-16px">
          <el-descriptions-item
            v-for="(columnItem, columnIndex) in columnList"
            :key="columnIndex"
            :label="columnItem.name"
          >
            <span v-if="columnItem.index == '1'">
              {{ descInfo.data.handClassificationName || descInfo.data.classificationName }}
            </span>
            <span v-else-if="columnItem.index == '2'">
              {{ descInfo.data.handLevelName || descInfo.data.levelName }}
            </span>
            <span v-else>
              {{ descInfo.data[`institutionFiled${columnItem.index}`] || '--' }}
            </span>
          </el-descriptions-item>
          <el-descriptions-item
            v-for="(extendItem, extendIndex) in extendList"
            :key="extendIndex"
            :label="extendItem.name"
          >
            <span v-if="extendItem.index == '3'">
              {{ descInfo.data.deadlineLevelName }}
            </span>
            <span v-else>
              {{ descInfo.data[`field${extendItem.index}`] || '--' }}
            </span>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <el-form ref="formRef" :rules="rules" :model="form" class="mt-12px" :disabled="sensitiveIf">
        <div class="mt-16px">
          <SubTitle title="复核结果信息" />
          <el-form-item
            required
            label="复核状态："
            prop="recheckStatus"
            v-if="params.sourceType != 'file' && params.sourceType != 'db'"
          >
            <el-radio-group v-model="form.recheckStatus">
              <el-radio label="1">通过</el-radio>
              <el-radio label="0">不通过</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="复核分类意见：">
            <template v-if="sensitiveIf">
              <Icon icon="svg-icon:tips" />
              <span style="color: #cccccc">归属机构与归属系统至少填写一项</span>
            </template>
          </el-form-item>
          <el-form-item
            v-for="(item, index) in columnList"
            :label="item.name"
            :prop="`institutionFiled${item.index}`"
            :rules="[{ required: item.required == '1', message: `${item.name}不能为空` }]"
            :key="index"
          >
            <!-- 字段1：分类 -->
            <el-cascader
              :filter-method="sysFilterMethod"
              @change="(e) => classChange(e, index + 1)"
              placeholder="请选择分类"
              v-model="form[`institutionFiled${item.index}`]"
              :options="classOptions"
              :props="{
                value: 'field1',
                label: 'field1_name',
                checkStrictly: true,
                expandTrigger: 'hover',
                emitPath: false
              }"
              v-if="item.index == '1'"
              filterable
            />
            <el-select
              v-else-if="item.index == '2'"
              v-model="form[`institutionFiled${item.index}`]"
              placeholder="请选择"
              @change="institutionFiledChange(item.index)"
            >
              <el-option
                v-if="sensitiveIf"
                :key="originClassification"
                :value="String(params.handLevel)"
                :label="params.handLevelName"
              />
              <template v-if="sensitiveIf">
                <el-option
                  v-for="item in levelList"
                  :key="item.levelCode"
                  :label="item.levelName"
                  :value="item.levelCode"
                />
              </template>
              <el-option
                v-for="sitem in cascaderAllOptions?.[`field${item.index - 1}`]"
                :key="sitem[`field${item.index}`]"
                :value="sitem[`field${item.index}`]"
                :label="sitem[`field${item.index}_name`]"
              />
            </el-select>
            <!-- 选择框字段 -->
            <el-select
              v-model="form[`institutionFiled${item.index}`]"
              placeholder="请选择"
              clearable
              allow-create
              filterable
              v-else-if="item.index == '3' && dropdownData"
              @change="
                () => {
                  institutionFiledChange(item.index)
                  timeFiledChange()
                }
              "
            >
              <el-option
                v-for="sitem in cascaderAllOptions[`field${item.index - 1}`]"
                :key="sitem[`field${item.index}`]"
                :value="sitem[`field${item.index}`]"
                :label="sitem[`field${item.index}_name`]"
              />
            </el-select>
            <!-- 输入框字段 -->
            <ns-input
              v-else-if="item.fillingMethod == '输入框'"
              v-model="form[`institutionFiled${item.index}`]"
              clearable
              placeholder="请输入"
              style="width: 200px"
            />
            <el-select
              v-else-if="item.fillingMethod == '选择器' && dropdownData"
              clearable
              v-model="form[`institutionFiled${item.index}`]"
              placeholder="请选择"
              @change="institutionFiledChange(item.index)"
            >
              <el-option
                v-for="sitem in cascaderAllOptions[`field${item.index - 1}`]"
                :key="sitem[`field${item.index}`]"
                :value="sitem[`field${item.index}`]"
                :label="sitem[`field${item.index}_name`]"
              />
            </el-select>
            <!-- 日期字段 -->
            <el-date-picker
              v-else-if="item.fillingMethod == '日期'"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model="form[`institutionFiled${item.index}`]"
              type="date"
              placeholder="选择日期"
            />
          </el-form-item>
          <!-- 扩展字段 -->
          <el-form-item
            v-for="(item, index) in extendList"
            :label="`${item.name}`"
            :prop="`recheckField${item.index}`"
            :rules="[{ required: item.required == '1', message: `${item.name}不能为空` }]"
            :key="index"
          >
            <el-select
              v-model="form[`recheckField${item.index}`]"
              placeholder="请选择"
              v-if="item.index == '3'"
            >
              <el-option
                v-for="item in levelList"
                :key="item.levelCode"
                :label="item.levelName"
                :value="item.levelCode"
              />
            </el-select>
            <ns-input
              v-else-if="item.fillingMethod == '输入框'"
              v-model="form[`recheckField${item.index}`]"
              clearable
              placeholder="请输入"
              style="width: 200px"
            />
            <el-select
              v-else-if="item.fillingMethod == '选择器'"
              clearable
              v-model="form[`recheckField${item.index}`]"
              placeholder="请选择"
            >
              <el-option
                v-for="(option, optionIndex) in item.presetContentMap"
                :key="optionIndex"
                :label="option"
                :value="option"
              />
            </el-select>
            <el-date-picker
              v-else-if="item.fillingMethod == '日期'"
              value-format="YYYY-MM-DD HH:mm:ss"
              v-model="form[`recheckField${item.index}`]"
              type="date"
              placeholder="选择日期"
              @change="dateChange(item.index)"
            />
          </el-form-item>
          <el-form-item label="复核说明" prop="recheckDesc" v-if="params.sourceType != 'file'">
            <ns-input
              v-model="form.recheckDesc"
              clearable
              type="textarea"
              placeholder="请输入复核说明"
              class="flex-1"
            />
          </el-form-item>
        </div>
      </el-form>
    </div>
    <div>
      <el-button type="primary" @click="confirm">确定</el-button>
      <el-button @click="closeOutDrawer">取消</el-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import SubTitle from '@/components/SubTitle/index.vue'
import { assetRecheck, getAssetDetail } from '@/api/assetList'
import { classificationTree } from '@/api/dataStandards/classification/index'
import { levelPage } from '@/api/strategyManage/level/index'
import { infoPage } from '@/api/dataStandards/info/index'
import {
  valueConfGetByValue,
  valueConfFieldValue,
  valueConfGetByValueTree
} from '@/api/dataStandards/assuranceValue/index'
import * as assuranceApi from '@/api/dataStandards/assurance/index'
import dayjs from 'dayjs'
import { sysFilterMethod } from '@/utils/selectFilter'
import useCascader from '@/hooks/event/useCascader'
const message = useMessage() // 消息弹窗
const { proxy } = getCurrentInstance() as any

const classOptions = ref([])
const formRef = ref()
const props = defineProps({
  params: {
    type: Object,
    default: () => {}
  },
  closeOutDrawer: Function
})

const form = ref({
  id: '',
  recheckClassification: '',
  recheckLevel: '',
  recheckImportance: '',
  recheckSensitiveDeadline: '',
  recheckDeadlineLevel: '',
  recheckDeadlineTimeNum: '',
  recheckDeadlineTimeUnit: '',
  recheckField: '',
  recheckStatus: '',
  recheckDesc: ''
})
const rules = {
  recheckStatus: [{ required: true, message: '复核状态不能为空', trigger: 'blur' }],
  recheckSensitiveDeadline: [{ required: true, message: '敏感期限不能为空', trigger: 'blur' }],
  recheckDeadlineTimeNum: [{ required: true, message: '时长不能为空', trigger: 'blur' }],
  recheckDeadlineTimeUnit: [{ required: true, message: '时间单位不能为空', trigger: 'blur' }],
  recheckDeadlineLevel: [{ required: true, message: '到期后敏感级别不能为空', trigger: 'blur' }],
  recheckClassification: [{ required: true, message: '分类不能为空', trigger: 'blur' }],
  recheckLevel: [{ required: true, message: '分级不能为空', trigger: 'blur' }],
  recheckDesc: [{ required: true, message: '复核说明不能为空', trigger: 'blur' }]
}

const descInfo = reactive({
  column: 1,
  columns: [
    { label: '表名称：', key: 'table' },
    { label: '表描述：', key: 'remark' },
    { label: '所属库：', key: 'database' }
  ],
  data: {}
})

const extendList = ref([
  {
    index: '1',
    name: '',
    required: '',
    fillingMethod: '输入框',
    presetContentMap: []
  }
])

const cascaderAllOptions = ref([])
// 数据选择修改后，控制后面字段的修改
let classChange = () => {}
let institutionFiledChange = () => {}
// 更新字段
function updateFields(selectedField, selectedValue) {
  const Index = parseInt(selectedField.replace('field', ''))
  // 找到与选定字段值匹配的第一个对象
  const matchedItem = downLists.value.find((item) => item[selectedField] === selectedValue)
  if (matchedItem) {
    // 更新其他字段的值（条件是只更新操作字段之后的字段）
    Object.keys(matchedItem).forEach((key) => {
      if (key !== selectedField && key.startsWith('field')) {
        const fieldIndex = parseInt(key.replace('field', ''))
        if (Index < fieldIndex)
          // 更新其他字段的值为匹配的对象的值
          form.value[`recheckInstitutionFiled${fieldIndex}`] = matchedItem[key]
      }
    })
  }
}

const dateChange = (index) => {
  if (index == '1') {
    timeFiledChange()
  }
}

const timeFiledChange = () => {
  let convertedTime = convertTimeFormat(form.value.institutionFiled3)
  if (!convertedTime) {
    let currentClass = allLevelList.value.find(
      (item) => item.levelCode == form.value.institutionFiled2
    )
    console.log('currentClass', currentClass)

    convertedTime =
      convertTimeFormat(currentClass?.deadlineTimeNum + currentClass?.deadlineTimeUnit) || {}
  }
  form.value.recheckField2 = dayjs(form.value.recheckField1)
    .add(Number(convertedTime.num), convertedTime.unit)
    .format('YYYY-MM-DD HH:mm:ss')
}
// 时间格式转换
function convertTimeFormat(timeString) {
  if (!timeString) {
    return
  }
  // 匹配数字和单位部分的正则表达式
  const regex = /(\d+)\s*([^0-9\s]+)/
  // 匹配结果
  const match = timeString.match(regex)
  const unitMap = new Map([
    ['年', 'year'],
    ['月', 'month'],
    ['天', 'day'],
    ['日', 'day']
  ])

  // 如果匹配成功，则返回 num 和 unit 对象
  if (match) {
    //单位不对则退出
    if (!unitMap.get(match[2])) {
      return false
    }
    return {
      num: parseInt(match[1]),
      unit: unitMap.get(match[2])
    }
  } else {
    // 如果匹配失败，返回空对象
    return false
  }
}

const recheckFieldList = ref({})
const confirm = async () => {
  /** 修复recheckInstitutionFiled1与recheckInstitutionFiled1未与institutionFiled1和InstitutionFiled2对应的bug */
  form.value[`recheckInstitutionFiled1`] = form.value.institutionFiled1
  form.value[`recheckInstitutionFiled2`] = form.value.institutionFiled2
  form.value[`recheckInstitutionFiled3`] = form.value.institutionFiled3

  for (let i = 1; i <= 20; i++) {
    recheckFieldList.value[`recheckField${i}`] = form.value[`recheckField${i}`]
    recheckFieldList.value[`recheckInstitutionFiled${i}`] =
      form.value[`recheckInstitutionFiled${i}`]
  }
  // 扩展字段
  form.value.recheckField = JSON.stringify(recheckFieldList.value)
  if (props.params.sourceType) {
    form.value.recheckStatus = '1'
  }
  console.log('hch form.value', form.value)
  formRef.value.validate(async (valid) => {
    if (valid) {
      form.value.handClassification = form.value?.institutionFiled1
      const data = await assetRecheck(form.value)
      if (data) {
        message.success('操作成功')
        props.params.callBack()
        props.closeOutDrawer()
      }
    }
  })
}

// 获取模板扩展字段列表
const getInfoList = async () => {
  const data = await infoPage({
    page: 1,
    pageSize: 20,
    dataStandardId: props.params.template,
    display: '1'
  })
  extendList.value = data.map((item) => {
    return {
      ...item,
      presetContentMap: item.presetContent ? JSON.parse(item.presetContent) : []
    }
  })
  getLevelList()
}

const columnList = ref([
  {
    index: '1',
    name: '',
    required: '',
    fillingMethod: '输入框',
    presetContentMap: []
  }
])
// 获取制度信息字段列表
const getAssuranceList = async () => {
  const data = await assuranceApi.assurancePage({
    dataStandardId: props.params.template,
    display: 1,
    page: 1,
    pageSize: 20
  })
  if (data.length > 0) {
    columnList.value = data
  } else {
    columnList.value = []
  }
}

// 获取模板下的分类树
const classificationList = ref([])
const getClassificationTree = async () => {
  const data = await classificationTree({
    standardId: props.params.template
  })
  classificationList.value = data
}

// 获取等级下拉列表
const levelList = ref([])
const allLevelList = ref([])
const getLevelList = async () => {
  const { data } = await levelPage({ page: 1, pageSize: 999 })
  const deadLineConf = extendList.value.find((item) => item.index === 3)
  if (deadLineConf && deadLineConf.presetContent && deadLineConf.presetContent !== '[]') {
    const presetCodes = JSON.parse(deadLineConf.presetContent)
    levelList.value = data.filter((item) => presetCodes.includes(item.levelCode))
  } else {
    levelList.value = data
  }
  levelList.value.map((item) => (item.levelCode = String(item.levelCode)))
  allLevelList.value = data
}

/** 查询下拉列表 */
const flattenDownList = ref([])
const downLists = ref([])
const dropdownData = ref({})
const getDownList = async () => {
  const data = await valueConfGetByValue({
    dataStandardId: props.params.template
  })
  let treeData = await valueConfGetByValueTree({
    dataStandardId: props.params.template
  })
  let { inFiledChange, typeChange, byValuetreeData, byValueData, cascaderSelectOptions } =
    await useCascader({
      treeData,
      data,
      listValue: ref([form.value]),
      tempLevelList: tempLevelList.value
    })

  classChange = typeChange
  institutionFiledChange = inFiledChange
  cascaderAllOptions.value = cascaderSelectOptions.value[0]
  if (data.length > 0) {
    downLists.value = byValueData
    flattenDownList.value = byValuetreeData
    dropdownData.value = convertToDropdownData(downLists.value)
  } else {
    downLists.value = []
    flattenDownList.value = []
    classOptions.value = setClassOptionsMap(flattenDownList.value)
  }
}
const convertToDropdownData = (data) => {
  const dropdownData = {}
  Object.keys(data[0]).forEach((key) => {
    if (key.startsWith('field')) {
      dropdownData[key] = Array.from(
        new Set(data.map((item) => item[key]).filter((value) => value !== ''))
      )
    }
  })
  return dropdownData
}

const tempClassList = ref([])
const tempLevelList = ref([])
const getClassLevelList = async () => {
  tempClassList.value = await valueConfFieldValue({
    dataStandardId: props.params.template,
    type: '1'
  })
  const data = await valueConfFieldValue({
    dataStandardId: props.params.template,
    type: '2'
  })
  tempLevelList.value = data.map((item) => {
    return {
      ...item,
      disabled: false
    }
  })
}

// 资产信息
const getAssetDetailFun = async () => {
  const { data } = await getAssetDetail({ id: props.params.id })
  form.value = data.recheckStatus == '1' ? data : props.params
  if (!!data.recheckField && data.recheckStatus == '1') {
    recheckFieldList.value = JSON.parse(form.value.recheckField)
    recheckFieldList.value.recheckField3 = recheckFieldList.value.recheckField3.toString()
    for (let i = 1; i <= 20; i++) {
      /**存在复核数据 使用复核数据 */
      form.value[`field${i}`] = recheckFieldList.value[`recheckField${i}`]
      form.value[`institutionFiled${i}`] = recheckFieldList.value[`recheckInstitutionFiled${i}`]

      form.value[`recheckField${i}`] = recheckFieldList.value[`recheckField${i}`]
      form.value[`recheckInstitutionFiled${i}`] =
        recheckFieldList.value[`recheckInstitutionFiled${i}`]
    }
  } else {
    for (let i = 1; i <= 20; i++) {
      form.value[`recheckField${i}`] = props.params[`field${i}`]
      form.value[`recheckInstitutionFiled${i}`] = props.params[`institutionFiled${i}`]
    }
  }
  if (props.params.type === '自动') {
    form.value.institutionFiled1 = form.value.classification
    form.value.institutionFiled2 = String(form.value.level)
  }
}
// 记录初始的分类
const originClassification = ref()
const sensitiveIf = ref(false)
onMounted(async () => {
  await getAssetDetailFun()
  await getClassLevelList()
  await getDownList()
  getInfoList()
  getAssuranceList()
  getClassificationTree()
  // getLevelList()

  console.log(props.params, 'adsad')
  descInfo.data = props.params
  if (props.params.dataType === 'column') {
    descInfo.column = 2
    descInfo.columns = [
      { label: '字段名称：', key: 'column' },
      { label: '字段类型：', key: 'columnType' },
      { label: '字段描述：', key: 'comment' },
      { label: '所属表：', key: 'table' },
      { label: '所属schema：', key: 'schema' },
      { label: '所属库：', key: 'database' }
    ]
  } else if (props.params.dataType === 'file') {
    descInfo.column = 1
    descInfo.columns = [
      { label: '文件名称：', key: 'fileName' },
      { label: '文件类型：', key: 'fileType' },
      { label: '文件大小：', key: 'fileSize' },
      { label: '文件指纹：', key: 'fileFingerprint' },
      { label: '归属机构：', key: 'deptName' },
      { label: '归属系统：', key: 'sysName' },
      { label: '数据标准：', key: 'templateName' }
    ]
  }
  sensitiveIf.value = Boolean(
    props.params.auditSensitiveStatus &&
      props.params.auditSensitiveStatus == '1' &&
      props.params.auditStatus == '2'
  )
  nextTick(() => {
    if (sensitiveIf.value) {
      form.value[`institutionFiled2`] = String(props.params.handLevel)
      originClassification.value = form.value[`institutionFiled1`]
    }
    if (Date.parse(props.params.deadlineTime) < Date.now() && sensitiveIf.value) {
      form.value.institutionFiled2 = props.params.recheckDeadlineLevel
        ? String(props.params.recheckDeadlineLevel)
        : String(props.params.deadlineLevel)
    }
  })
})
const setClassOptionsMap = (data) => {
  return data.map((item) => {
    item.field1_name = tempClassList.value.find((fitem) => fitem.key == item.field1).value
    item.disabled = item.isSelect == '0'
    item.children.length && setClassOptionsMap(item.children)
    return item
  })
}

const handleCheckclassOptions = (list, targetValue) => {
  for (const item of list) {
    // 使用 for...of 遍历数组
    if (item.field1 === targetValue) {
      return true // 找到直接返回
    }
    // 检查是否存在 children 并且是数组且长度大于0
    if (item.children && Array.isArray(item.children) && item.children.length > 0) {
      // 递归检查子节点，并立即返回结果
      const found = handleCheckclassOptions(item.children, targetValue)
      if (found) return true
    }
  }
  return false // 遍历完所有项未找到
}

watch(
  () => [tempClassList.value, downLists.value],
  () => {
    if (downLists?.value?.length > 0 && tempClassList?.value?.length > 0) {
      classOptions.value = setClassOptionsMap(flattenDownList.value)
      const isInclude = handleCheckclassOptions(classOptions.value, form.value.institutionFiled1)
      if (form?.value?.institutionFiled1 && !isInclude) {
        form.value.institutionFiled1 = classOptions.value[0]?.field1
        classChange(classOptions.value[0]?.field1, 1)
      } else {
        classChange(form.value.institutionFiled1, 1)
      }
    }
  }
)
</script>

<style scoped lang="scss">
:deep(.el-table .el-form-item--default) {
  margin-bottom: 0 !important;
}
</style>
